package cn.com.smart.framework.aspectj;

import cn.com.smart.common.utils.Cache;
import cn.com.smart.common.utils.JWTUtil;
import cn.com.smart.framework.aspectj.lang.annotation.AppPermissions;
import cn.com.smart.module.system.menu.service.IMenuService;
import cn.com.smart.module.system.user.domain.User;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

@Component
public class AppInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private IMenuService menuService;
    /**
     * 检查是否已经登录
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("ms-token");
        User user= JWTUtil.parseToken(token);
        if(user==null){
            JSONObject outputMSg = new JSONObject();
            outputMSg.put("code", 500);
            outputMSg.put("msg", "请登陆后访问");
            output(outputMSg.toJSONString(), request, response);
            return false;
        }
        //获取方法上权限注解
        HandlerMethod method = (HandlerMethod) handler;
        AppPermissions permissions=method.getMethodAnnotation(AppPermissions.class);
        //带有权限注解且不为管理员则进行权限验证
        if(permissions!=null&&!user.getOrgId().equals(0L)){
            Set<String> menus;
            //从缓存获取用户权限字符串，没有则从数据库查并添加到缓存
            menus= (Set<String>) Cache.get(user.getUserId().toString());
            if(menus==null){
                menus=menuService.selectPermsByUserId(user.getUserId());
                Cache.put(user.getUserId().toString(),menus);
            }
           // if(menus.add(permissions.value())==true){
            if(menus.contains(permissions.value())==false){
                JSONObject outputMSg = new JSONObject();
                outputMSg.put("code", 500);
                outputMSg.put("msg", "您没有权限访问该接口");
                output(outputMSg.toJSONString(), request, response);
                return false;
            }
        }
        return true;
    }

    /**
     * 给前端返回数据
     * @param jsonStr 返回的json
     * @param request
     * @param response
     * @throws IOException
     */
    public void output(String jsonStr, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String header = request.getHeader("Origin");
        response.setContentType("text/html;charset=UTF-8;");
        response.setHeader("Access-Control-Allow-Origin", header);
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,XFILENAME,XFILECATEGORY,XFILESIZE,token");
        PrintWriter out = response.getWriter();
        out.println(jsonStr);
        out.flush();
        out.close();
    }
}
